package hash;


import java.util.HashMap;

/**
 * Created by JiaJia on 2019/5/25 0025.
 * 最长和谐序列
 * 和谐序列中最大数和最小数之差正好为 1，应该注意的是序列的元素不一定是数组的连续元素。
 * Input: [1,3,2,2,5,2,3,7]
 * Output: 5
 * Explanation: The longest harmonious subsequence is [3,2,2,2,3].
 */
public class LongestHarmoniousSubsequence {
    private static int longestSubsequence(int[] nums){
        HashMap<Integer,Integer> map=new HashMap<>();
        for (int num:nums) {
            map.put(num,map.getOrDefault(num,0)+1);
        }
        int longest=0;
        for (int num:map.keySet()) {
            if (map.containsKey(num+1)){
                longest=Math.max(longest,map.get(num)+map.get(num+1));
            }
        }
        return longest;
    }

    public static void main(String[] args) {
        int[] num={1,3,2,2,5,2,3,7};
        System.out.println(longestSubsequence(num));
    }
}